//
//  DocumentThumbView.m
//  Documents
//
//  Created by Alex Di Mango 
//  Copyright (c) 2012 Whardoo.com -  All rights reserved.
//

#import "DocumentThumbView.h"
#import "DocumentsViewController.h"
#import "NSObject+ThumbViewMaker.h"
#import "SplittedDocumentViewController.h"
#import "DocumentsColors.h"
#import "DocumentsConstants.h"
#import "MasterScrollView.h"

#define zoomed 0.5
#define CANCEL_TAG 1
#define RENAME_TAG 2

@implementation DocumentThumbView
@synthesize docId,docImage,docRefImage,docMarked,docName,dragAndDropView,droppableDelegate;
@synthesize webView,loadedWebView,activityView;
@synthesize swipeButtonR,swipeButtonL,deletingShow,renamingShow;
@synthesize isScrolling;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

#pragma mark - UIWebviewdelegate Thumb

-(void)getMSThumb:(NSURL *)documentURL{
    webView = [[UIWebView alloc] init];
    webView.frame = CGRectMake(35, 6., 90., 127.);
    webView.scalesPageToFit = YES;
    webView.backgroundColor = [UIColor whiteColor];
    webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    webView.delegate = self;    
    NSURLRequest *request = [NSURLRequest requestWithURL:documentURL];
    [webView loadRequest:request];     
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{

}

-(void)drawSelectionRect{
    UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(29, 0., 102., 139.)];
    image.alpha = 0.0;
    image.tag = 888;
    image.layer.masksToBounds = YES;
    image.layer.borderColor = [[UIColor orangeColor] CGColor];
    image.layer.borderWidth = 2.0f;
    [self addSubview:image];
    [UIView animateWithDuration:0.6 animations:^{
        image.alpha = 1;
    }];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {    
    if(!loadedWebView){
        UIGraphicsBeginImageContext(CGSizeMake( 90., 127.));
        CGContextRef context = UIGraphicsGetCurrentContext();
        [self.webView.layer renderInContext:context];
        self.docImage.alpha = 0;
        self.docRefImage.alpha = 0;
        [UIView animateWithDuration:0.5 animations:^{
            UIImage *thumbnail = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext(); 
            self.docImage.image = thumbnail;
            self.docRefImage.image = [self reflectedImage:self.docImage withHeight:30];
            self.docImage.alpha = 1;
            self.docRefImage.alpha = 0.4;
        }];
        //[activityView hidesWhenStopped];
        //[activityView stopAnimating];
        
        [self.activityView stopAnimating];                
        [self setLoadedWebView:YES]; 
        MyDocument *myDoc = [MyDocument getDocumentWithId:[NSNumber numberWithInt:self.tag]];
        
        NSData *imageData = UIImagePNGRepresentation(self.docImage.image);
        NSData *imageRefData = UIImagePNGRepresentation(docRefImage.image); 
        [myDoc setValue:imageData forKey:@"image"];
        [myDoc setValue:imageRefData forKey:@"imageRef"];
    }    
} 


#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UIButton class]]){
        return NO;
    }
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return NO;
}

-(void)tapGestureAction:(UILongPressGestureRecognizer *)gesture{
    MasterScrollView *master = (MasterScrollView *)self.superview; 
    [master showDocument:[NSNumber numberWithInt:self.tag ]];        
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    if(deletingShow){
        [self.swipeButtonR removeFromSuperview];
        [self setDeletingShow:NO];  
    }
    if(renamingShow){
        [self.swipeButtonL removeFromSuperview];
        [self setRenamingShow:NO];  
    }
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{   
    
    UITouch *touch = [touches anyObject];

    
    DocumentsViewController *home = self.superview.superview.nextResponder; 
    [home handleSingleTap:touch];

    [UIView beginAnimations:nil context:docImage.image.CGImage]; 
    [UIView setAnimationDuration:0.2]; 
    //   [UIView setAnimationRepeatAutoreverses:YES];
    self.docImage.transform = CGAffineTransformScale(self.docImage.transform, 1+zoomed, 1+zoomed);
    self.docRefImage.transform = CGAffineTransformScale(self.docRefImage.transform, 1+zoomed, 1+zoomed);
    self.docMarked.transform = CGAffineTransformScale(self.docMarked.transform, 1+zoomed, 1+zoomed);

    
    self.docImage.transform = CGAffineTransformIdentity;
    self.docRefImage.transform = CGAffineTransformIdentity;
    self.docMarked.transform = CGAffineTransformIdentity;

    
    [UIView commitAnimations]; 
    
}

-(void)swipeGestureActionRight:(UILongPressGestureRecognizer *)gesture{
    
    [self setDeletingShow:YES];
    swipeButtonR = [UIButton buttonWithType:UIButtonTypeCustom];
    
    // Round button corners
    CALayer *btnLayer = [swipeButtonR layer];
    [btnLayer setMasksToBounds:YES];
    [btnLayer setCornerRadius:5.0f];
    
    [swipeButtonR setTitle:@"Delete" forState:UIControlStateNormal];
    [swipeButtonR setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [swipeButtonR setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    
    
    swipeButtonR.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    swipeButtonR.layer.borderColor = [UIColor blackColor].CGColor;
    swipeButtonR.layer.borderWidth = 0.5f;
    swipeButtonR.layer.cornerRadius = 5.0f;
    swipeButtonR.alpha = 1;
    
    [swipeButtonR addTarget:self action:@selector(deleteItem) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self addSubview:swipeButtonR];
    [self.superview bringSubviewToFront:swipeButtonR];
    
    
    [UIView animateWithDuration:0.2 delay: 0.0 options: UIViewAnimationOptionTransitionFlipFromTop animations:^{ 
        [swipeButtonR setFrame:CGRectMake(36, 30, 88, 35)]; 
        // Draw a custom gradient
        CAGradientLayer *btnGradient = [CAGradientLayer layer];
        btnGradient.frame = swipeButtonR.bounds;
        btnGradient.colors = [NSArray arrayWithObjects:
                              (id)[DELETE_RED CGColor],
                              (id)[DELETE_RED_GRADIENTE CGColor],
                              nil];
        [swipeButtonR.layer insertSublayer:btnGradient atIndex:0];
    } 
                     completion:^(BOOL finished){ }
     ];
}

-(void)swipeGestureActionLeft:(UILongPressGestureRecognizer *)gesture{
    [self setRenamingShow:YES];
    swipeButtonL = [UIButton buttonWithType:UIButtonTypeCustom];
    
    // Round button corners
    CALayer *btnLayer = [swipeButtonL layer];
    [btnLayer setMasksToBounds:YES];
    [btnLayer setCornerRadius:5.0f];
    
    [swipeButtonL setTitle:@"Rename" forState:UIControlStateNormal];
    [swipeButtonL setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [swipeButtonL setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    
    
    swipeButtonL.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    swipeButtonL.layer.borderColor = [UIColor blackColor].CGColor;
    swipeButtonL.layer.borderWidth = 0.5f;
    swipeButtonL.layer.cornerRadius = 5.0f;
    swipeButtonL.alpha = 1;
    
    [swipeButtonL addTarget:self action:@selector(renameItem) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:swipeButtonL];
    [self.superview bringSubviewToFront:swipeButtonL];
    
    [UIView animateWithDuration:0.2 delay: 0.0 options: UIViewAnimationCurveLinear animations:^{ 
        [swipeButtonL setFrame:CGRectMake(36, 30, 88, 35)]; 
        // Draw a custom gradient
        CAGradientLayer *btnGradient = [CAGradientLayer layer];
        btnGradient.frame = swipeButtonL.bounds;
        btnGradient.colors = [NSArray arrayWithObjects:
                              (id)[RENAME_GREEN CGColor],
                              (id)[RENAME_GREEN_GRADIENTE CGColor],
                              nil];
        
        [swipeButtonL.layer insertSublayer:btnGradient atIndex:0];
    } 
                     completion:^(BOOL finished){ }
     ];
}


-(void)deleteItem
{
    NSLog(@"Delete %@",self.docName);
    if(deletingShow){
        [self.swipeButtonR removeFromSuperview];
        [self setDeletingShow:NO];  
    }
    self.alpha = 0.5;    
    // self.folderToDelete = [self.folders objectAtIndex:indexPath.row];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedStringFromTable(@"error", @"Documents", nil) message:NSLocalizedStringFromTable(@"confirmDeleteDoc", @"Documents", nil) delegate:self cancelButtonTitle:NSLocalizedStringFromTable(@"cancel", @"Documents", nil) otherButtonTitles:NSLocalizedStringFromTable(@"delete", @"Documents", nil), nil];
    [alert setTag:CANCEL_TAG];
    [alert show];    
}
-(void)renameItem
{
    NSLog(@"Rename %@",self.docName);
    if(renamingShow){
        [self.swipeButtonL removeFromSuperview];
        [self setRenamingShow:NO];  
    }    
    self.alpha = 0.5;    
    UIAlertView *msg = [[UIAlertView alloc]initWithTitle:NSLocalizedStringFromTable(@"rename", @"Documents", nil) message:NSLocalizedStringFromTable(@"renameMsg", @"Documents", nil) delegate:self
                                       cancelButtonTitle:NSLocalizedStringFromTable(@"cancel", @"Documents", nil) otherButtonTitles:NSLocalizedStringFromTable(@"rename", @"Documents", nil), nil ];   
    
    [msg setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [msg setTag:RENAME_TAG];
    [msg show];
    
    
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    MyDocument *myDoc = [MyDocument getDocumentWithId:[NSNumber numberWithInt:self.tag]];
    //Delete
    if(alertView.tag == CANCEL_TAG && buttonIndex == alertView.firstOtherButtonIndex) 
    {    
            DocumentsViewController *home = (DocumentsViewController *)self.superview.superview.nextResponder; 
            [home setSelectedDocument:nil];
            [home setSelectedFolder:myDoc.myFolder];
            [MyDocument deleteSelectedDocument:myDoc];
            [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_FOLDERS_AND_DOCS object:self];
    }
    //Rename
    else if(alertView.tag == RENAME_TAG && buttonIndex == alertView.firstOtherButtonIndex) 
    {    
            [myDoc setTitle:[[alertView textFieldAtIndex:0] text]];
            [[NSNotificationCenter defaultCenter] postNotificationName:REFRESH_FOLDERS_AND_DOCS object:self];
        }
    //Cancel button
    else {
        self.alpha = 1.0;
    }
}

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
    if(alertView.tag == RENAME_TAG){
    NSString *inputText = [[alertView textFieldAtIndex:0] text];
    if( [inputText length] >= 1 )
    {
        return YES;
    }
    else
    {
        return NO;
    }
    }   return YES;

}


-(void)longGestureAction:(UILongPressGestureRecognizer *)gesture{
    UIView *docThumb= (UIView *)[gesture view];
    
    switch ([gesture state]) {
        case UIGestureRecognizerStateBegan:{          
                [self dragAndDropThumbViewController:self  draggingGestureWillBegin:gesture forThumb:docThumb];
                UIView *draggedView = [self dragAndDropThumbViewControllerView:self ];
                //switch the view the gesture is associated with this will allow the dragged view to continue on where the cell leaves off from
                [draggedView addGestureRecognizer:[[docThumb gestureRecognizers]objectAtIndex:0]]; 
                [self dragAndDropThumbViewController:self draggingGestureDidBegin:gesture forThumb:docThumb];
        }
            break;
        case UIGestureRecognizerStateChanged:{
            [self dragAndDropThumbViewController:self draggingGestureDidMove:gesture];
        }
            break;
        case UIGestureRecognizerStateEnded:{
            UIView *draggedView = [self dragAndDropThumbViewControllerView:self];
            if(draggedView==nil)
                return;
            
            [self.droppableDelegate dragAndDropThumbViewController:self droppedGesture:gesture];
            [self dragAndDropThumbViewController:self draggingGestureDidEnd:gesture];
        }
            break;
        default:
            break;
    }
}
#pragma mark - DragAndDrop

-(void)dragAndDropThumbViewController:(UIView *)ddtvc draggingGestureDidBegin:(UIGestureRecognizer *)gesture forThumb:(UIView *)cell
{
    cell.alpha = 0.6;
    
}

-(void)dragAndDropThumbViewController:(UIView *)ddtvc draggingGestureWillBegin:(UIGestureRecognizer *)gesture forThumb:(UIView *)cell{
    
    UIGraphicsBeginImageContext(cell.bounds.size);
    [cell.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *iv = [[UIImageView alloc] initWithImage:img];
    iv.transform = CGAffineTransformMakeScale(0.8, 0.8);
    [iv setFrame:CGRectMake(0, 0, iv.frame.size.width, iv.frame.size.height)];
    
    UIView *dragAndDrop = [[UIView alloc]initWithFrame:iv.frame];

    self.dragAndDropView = dragAndDrop;
    
    [self.dragAndDropView addSubview:iv];
    
    [self.dragAndDropView setCenter:[gesture locationInView:self]];
    
    [self addSubview:self.dragAndDropView];
    
    [self.superview bringSubviewToFront:self];
    

}

-(void)dragAndDropThumbViewController:(UIView *)ddtvc draggingGestureDidMove:(UIGestureRecognizer *)gesture{
    [self.dragAndDropView setCenter:[gesture locationInView:self]];
    
    CGPoint p = [gesture locationInView:self.superview.superview];
    
    //start scrolling
  //  NSLog(@" PUNTO %@", NSStringFromCGPoint(p));   
    CGFloat yy = p.y;    
    if(yy<-5){
        [self inc];
    }

}


-(void)inc{
    DocumentsViewController *root = self.superview.superview.nextResponder;
    MasterScrollView *masterView = [root masterView];
    CGPoint offset = [masterView contentOffset];
    if(offset.y!=0 && offset.y >50){
        offset.y = offset.y-50;
        [masterView setContentOffset:offset animated:YES];
        [masterView flashScrollIndicators];
    }
}


-(void)dragAndDropThumbViewController:(UIView *)ddtvc draggingGestureDidEnd:(UIGestureRecognizer *)gesture{
    
    [self.dragAndDropView removeFromSuperview];
    self.dragAndDropView = nil;
    ddtvc.alpha = 1.0;
}


-(UIView *)dragAndDropThumbViewControllerView:(UIView *)ddtvc{
    return self.dragAndDropView;
}

-(id)dragAndDropThumbViewControllerSelectedItem
{
    return nil;
}


- (void)dealloc {

}







@end
